package com.hunttown.mes.common.utils;

import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * created by wangjunfu on 2019-05-21
 */
public class GeneralUtils {
    /**
     * 遍历实体类的属性及属性值
     *
     * @param json FastJson
     * @param cls  实体类class
     * @return map
     */
    public static Map<String, Object> ergodicModel(String json, Class cls) {
        try {
            Field[] fields = cls.getDeclaredFields();
            Map<String, Object> map = new HashMap<>();
            for (Field f : fields) {
                f.setAccessible(true);
                map.put(f.getName(), f.get(FastJsonUtils.fromJSON(json, cls)));
            }
            return map;

        } catch (Exception ex) {
            //todo
            return null;
        }
    }

    /**
     * 转整型
     *
     * @param obj 需要转换的对象
     * @return int
     */
    public static Integer ObjectToInt(Object obj) {
        if (obj == null) {
            return 0;
        }

        String str = String.valueOf(obj);
        return Integer.parseInt(str);
    }

    /**
     * 生成以时间为基准的号码
     *
     * @param random 末位生成几位随机数 最长4位
     * @param prefix 前缀 最长2位
     * @param suffix 后缀 最长2位
     * @return 号码
     */
    public static String GenTimeSeries(Integer random, String prefix, String suffix) {
        SimpleDateFormat ft = new SimpleDateFormat("yyMMddHHmmss");
        String keyCode = ft.format(new Date());

        //N位随机数(最长18位)
        if (random > 0 && random <= 4) {
            keyCode = String.format("%s%s", keyCode, GetRandomUtils.GetRandomNumber(random));
        }

        if (StringUtils.isNotBlank(prefix) && prefix.length() <= 2) {
            keyCode = String.format("%s%s", prefix, keyCode);
        }

        if (StringUtils.isNotBlank(suffix) && suffix.length() <= 2) {
            keyCode = String.format("%s%s", keyCode, suffix);
        }

        //最长(20位)
        return keyCode;
    }

    /**
     * 生成以日期为基准的号码
     *
     * @param num {订单号}
     * @param len 位数，不够补0
     * @return 号码
     */
    public static String GenDateSeries(Integer num, Integer len) {
        SimpleDateFormat ft = new SimpleDateFormat("yyMMdd");
        String keyCode = ft.format(new Date());
        keyCode += StringUtils.padLeft(num, len);

        return keyCode;
    }

    /**
     * 生成时间戳（秒级）
     *
     * @return 时间戳
     */
    public static String GenTimestamp() {
        return GenTimeSeries(0, null, null);
    }

    /**
     * 生成电价key
     *
     * @return key：年年月月时时
     */
    public static String GenElectricKey() {
        SimpleDateFormat ft = new SimpleDateFormat("yyMMHH");
        return ft.format(new Date());
    }

    //年年月月
    public static String GenElectricDayKey() {
        SimpleDateFormat ft = new SimpleDateFormat("yyMM");
        return ft.format(new Date());
    }

    public static String GenElectricDayKey(String dateStr) {
        if (StringUtils.isBlank(dateStr)) {
            return GenElectricDayKey();
        }

        dateStr = dateStr.replaceAll("-", "").replaceAll(" ", "").replaceAll(":", "");
        System.out.println(dateStr);
        return dateStr.substring(2, 6);
    }

    /**
     * 不够位数的在前面补0，保留num的长度位数字
     *
     * @param code 字符
     * @param num  要保留的位数
     * @return 结果
     */
    public static String autoGenericCode(Integer code, int num) {
        StringBuilder p = new StringBuilder();
        for (int i = 0; i < num; i++) {
            p.append("0");
        }

        DecimalFormat df = new DecimalFormat(p.toString());
        return df.format(code);
    }

    /**
     * 将table_name格式化为tableName等
     *
     * @param field 字段
     * @return 字段
     */
    public static String standardFields(String field) {
        if (StringUtils.isBlank(field)) {
            return field;
        }

        StringBuilder newField = new StringBuilder();
        String[] arr = field.split("_");
        for (String item : arr) {
            if (newField.toString().equals("")) {
                newField = new StringBuilder(item);
            } else {
                newField.append(upperFirstLatter(item));
            }
        }

        return newField.toString();
    }

    /**
     * 首字母大写
     *
     * @param latter 设置的字符串
     * @return latter
     */
    private static String upperFirstLatter(String latter) {
        if (StringUtils.isBlank(latter)) {
            return latter;
        }

        if (latter.length() == 1) {
            return latter;
        }

        return latter.substring(0, 1).toUpperCase().concat(latter.substring(1).toLowerCase());
    }


    /**
     * 如果没有获取到配置的JS版本号
     * 那么每天生成一个版本号
     *
     * @return version
     */
    public static String getEveryDayVersion() {
        String version = "9.9.9.9";

        try {
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            Date start = df.parse("1990-01-01");
            Long start_time = start.getTime();
            Long end_time = new Date().getTime();
            long diff_time = end_time - start_time;
            version = String.format("%s.0", diff_time / (1000 * 60 * 60 * 24));

        } catch (ParseException e) {
            e.printStackTrace();
        }

        return version;
    }

    // 将标题进行编码
    public static String encodeFilename(String fileName) {
        if (StringUtils.isBlank(fileName)) {
            return fileName;
        }

        String[] titles = fileName.split("\\.");
        String encodename = titles[0];

        try {
            encodename = URLEncoder.encode(encodename, "UTF-8");
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        if (titles.length > 1) {
            return String.format("%s.%s", encodename, titles[1]);
        } else {
            return encodename;
        }
    }

    // 通过 contenttype 获取相应的 icon 图标
    public static String getContentTypeUrl(String contenttype) {
        String pic = "";

        if (contenttype.contains(".document") || contenttype.contains("msword")) {
            pic = "/static/assets/images/doc-icon/Word.png";
        } else if (contenttype.contains(".sheet")) {
            pic = "/static/assets/images/doc-icon/Excel.png";
        } else if (contenttype.contains(".presentation")) {
            pic = "/static/assets/images/doc-icon/PowerPoint.png";
        } else if (contenttype.contains("octet-stream")) {
            pic = "/static/assets/images/doc-icon/rar.jpg";
        } else if (contenttype.contains("text")) {
            pic = "/static/assets/images/doc-icon/txt.jpg";
        } else if (contenttype.contains("pdf")) {
            pic = "/static/assets/images/doc-icon/pdf.png";
        } else if (contenttype.contains("video")) {
            pic = "/static/assets/images/doc-icon/video.png";
        } else if (!contenttype.contains("image")) {
            pic = "/static/assets/images/doc-icon/Office.png";
        }

        return pic;
    }

    // 通过 contenttype 获取相应的类型
    public static String getContentType(String contenttype) {
        String type = "";

        if (contenttype.contains(".document") || contenttype.contains("msword")) {
            type = "word";
        } else if (contenttype.contains(".sheet")) {
            type = "excel";
        } else if (contenttype.contains(".presentation")) {
            type = "ppt";
        } else if (contenttype.contains("text")) {
            type = "txt";
        } else if (contenttype.contains("pdf")) {
            type = "pdf";
        } else {
            type = "img";
        }

        return type;
    }

    public static void main(String[] args) throws Exception {
        /* 注释
        DecimalFormat df = new DecimalFormat("0000");
        System.out.println(df.format(2));
        System.out.println(df.format(4));
        System.out.println(df.format(6));

        String nastr = "王君富2019年10月2日-10月8日的报销单";
        nastr = nastr.replace("报销单", "");
        System.out.println(nastr);
        */

        //String orderno = GenTimeSeries(0, null, null);
        //String orderno1 = GenElectricKey();
        //String orderno2 = GenElectricDayKey();
        //System.out.println("订单号1：" + orderno1);
        //System.out.println("订单号2：" + orderno2);

        String dateStr = "2022-10-31"; //DateConvertUtils.dateToStr(new Date());
        String orderno2 = GenElectricDayKey(dateStr);
        System.out.println("订单号2：" + dateStr + "/" + orderno2);
    }
}